<template>
  <el-container class="p-20" style="height: 100%;">
    <el-header style="font-size: 12px;height: auto;">
      <el-row :gutter="10">
        <el-col :xl="3" :lg="5" :md="6" :sm="8" :xs="8">
          <el-input v-model="search.keyword" clearable placeholder="请输入订单号、名称查询"/>
        </el-col>
        <el-col :xl="5" :lg="7" :md="8" :sm="8" :xs="8">
          <el-date-picker
            v-model="applyTimeRange"
            :picker-options="pickerOptions"
            type="datetimerange"
            range-separator="-"
            start-placeholder="申请开始日期"
            end-placeholder="申请结束日期"
            align="right"
            class="full-width-i"/>
        </el-col>
        <el-col :xl="3" :lg="4" :md="6" :sm="6" :xs="8">
          <el-select v-model="search.invoiceStatus" clearable placeholder="开票状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-col>
        <el-col :lg="3" :md="4" :sm="6" :xl="2" :xs="4">
          <el-button icon="el-icon-search" type="primary" @click="loadInvoiceTable">搜索</el-button>
        </el-col>
        <el-col :lg="3" :md="4" :sm="6" :xl="2" :xs="4">
          <el-button icon="el-icon-download" type="warning" @click="exportInvoice">导出</el-button>
        </el-col>
      </el-row>
    </el-header>

    <el-main>
      <el-table :data="invoiceTableData" height="600">
        <el-table-column label="序" type="index" fixed="left"/>
        <el-table-column label="操作" fixed="left">
          <template slot-scope="scope">
            <div v-show="scope.row.invoiceStatus === 'applying'">
              <el-button
                size="small"
                type="text"
                @click="invoiceDialog(scope.$index, scope.row)"
              >开票</el-button>
            </div>
            <div v-show="scope.row.invoiceStatus === 'invoiced'">
              <el-button
                size="small"
                type="text"
                @click="invoiceInfoDialog(scope.$index, scope.row)"
              >查看</el-button>
            </div>

          </template>
        </el-table-column>
        <el-table-column label="业务类型" prop="businessTypeText"/>
        <el-table-column label="业务单号" prop="businessNumber" width="180">
          <template slot-scope="scope">
            <span v-show="scope.row.businessType === 'order'">{{ scope.row.businessNumber }}</span>
            <el-button v-show="scope.row.businessType === 'shop'" type="text" @click="openSkuInfo(scope.row)">{{ scope.row.businessNumber }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="开票状态" prop="invoiceStatusText">
          <template slot-scope="scope">
            <span v-show="scope.row.invoiceStatus === 'applying'">未开票</span>
            <span v-show="scope.row.invoiceStatus === 'invoiced'">已开票</span>
          </template>
        </el-table-column>
        <el-table-column label="开票类型" prop="invoiceBusinessTypeText" align="center"/>
        <el-table-column label="发票类型" align="center">
          <template slot-scope="scope">
            <span v-show="scope.row.invoiceType === 'electronic'">电子</span>
            <el-button
              v-show="scope.row.invoiceType === 'paper'"
              size="small"
              type="text"
              @click="receiptDialog(scope.$index, scope.row)"
            >纸质</el-button>
          </template>
        </el-table-column>
        <el-table-column label="开票金额" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.invoiceAmount===null? "--" :('￥ '+scope.row.invoiceAmount.toFixed(2)) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请日期" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.invoiceApplyTime===null? "--" :scope.row.invoiceApplyTime |moment("YYYY-MM-DD") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="invoiceName"/>
        <el-table-column label="纳税人识别号" prop="invoiceNumber" width="180"/>
        <el-table-column label="电话" prop="invoicePhone" width="120"/>
        <el-table-column label="地址" prop="invoiceAddress" width="180"/>
        <el-table-column label="邮箱" prop="userEmail" width="120"/>
        <el-table-column label="开户行" prop="invoiceBank"/>
        <el-table-column label="账号" prop="invoiceBankAccount" width="120"/>
        <el-table-column label="操作人" width="120">
          <template
            v-show="scope.row.updaterName===null"
            slot-scope="scope"
          >{{ scope.row.createrName===null? "--" :scope.row.createrName }}</template>
          <template
            v-show="scope.row.updaterName"
            slot-scope="scope"
          >{{ scope.row.updaterName===null? "--" :scope.row.updaterName }}</template>
        </el-table-column>
        <el-table-column label="操作时间" width="120">
          <template
            v-show="scope.row.updateDatetime===null"
            slot-scope="scope"
          >{{ scope.row.createDatetime===null? "--" :scope.row.createDatetime |moment("YYYY-MM-DD") }}</template>
          <template
            v-show="scope.row.updateDatetime"
            slot-scope="scope"
          >{{ scope.row.updateDatetime===null? "--" :scope.row.updateDatetime |moment("YYYY-MM-DD") }}</template>
        </el-table-column>
      </el-table>

      <el-dialog
        v-el-drag-dialog
        :center="true"
        :close-on-click-modal="false"
        :show-close="true"
        :visible.sync="dialogInvoiceVisible"
        width="30%"
      >
        <el-form :label-position="labelPosition" :model="invoice" label-width="120px">
          <el-form-item label="订单号">
            <span class="text-wrap">{{ invoice.businessNumber }}</span>
          </el-form-item>
          <el-form-item label="名称">
            <span class="text-wrap">{{ invoice.invoiceName }}</span>
          </el-form-item>
          <el-form-item label="类型">
            <span class="text-wrap">{{ invoice.invoiceBusinessTypeText }}</span>
          </el-form-item>
          <el-form-item label="电子发票地址">
            <el-input v-model="invoice.invoiceMakeAddress"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="invoice.invoiceMakeRemark" type="textarea"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveInvoice">保 存</el-button>
        </div>
      </el-dialog>

      <el-dialog
        v-el-drag-dialog
        :show-close="true"
        :visible.sync="dialogInvoiceInfoVisible"
        width="40%"
      >
        <el-form :label-position="labelPosition" label-width="150px">
          <el-form-item label="电子发票地址">
            <span class="text-wrap">{{ invoice.invoiceMakeAddress }}</span>
          </el-form-item>
          <el-form-item label="备注">
            <span class="text-wrap">{{ invoice.invoiceMakeRemark }}</span>
          </el-form-item>
        </el-form>
      </el-dialog>

      <el-dialog
        v-el-drag-dialog
        :show-close="true"
        :visible.sync="dialogReceiptVisible"
        width="40%"
      >
        <el-form :label-position="labelPosition" label-width="150px">
          <el-form-item label="收件人">
            <span class="text-wrap">{{ invoice.userName }}</span>
          </el-form-item>
          <el-form-item label="电话">
            <span class="text-wrap">{{ invoice.userPhone }}</span>
          </el-form-item>
          <el-form-item label="地址">
            <span class="text-wrap">{{ invoice.userAddress }}</span>
          </el-form-item>
        </el-form>
      </el-dialog>
      <component :modal-data="modalData" :is="modal" :refresh="loadInvoiceTable" @close="closeChild"/>
    </el-main>
  </el-container>
</template>

<style>
.el-header {
  background-color: #b3c0d1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
.full-width-i {
  width: 100% !important;
}
</style>

<script>
import { getInvoiceList, getInvoice, saveInvoice, exportInvoice } from '@/api/settle/invoice'
import elDragDialog from '@/directive/el-dragDialog' // base on element-ui
import constant_ from '@/components/common/constant'
import { download } from '@/api/utils'
import skuInfo from './skuInfo'
export default {
  directives: { elDragDialog },
  components: { skuInfo },
  data() {
    return {
      search: {
        keyword: '',
        applyStartTime: '',
        applyEndTime: '',
        invoiceStatus: ''
      },
      modal: null,
      modalData: {},
      modelShowTab: null,
      dialogInvoiceVisible: false,
      dialogReceiptVisible: false,
      dialogInvoiceInfoVisible: false,
      labelPosition: 'left',
      invoice: {},
      invoiceTableData: [],
      statusOptions: [
        { label: '未开票', value: 0 },
        { label: '已开票', value: 1 }
      ],
      pickerOptions: constant_.pickerOptions,
      applyTimeRange: ''
    }
  },
  created() {
    const self = this
    self.loadInvoiceTable()
  },
  methods: {
    // 关闭子组件
    closeChild() {
      this.modal = null
    },
    packSearchData() {
      const self = this
      if (self.applyTimeRange && self.applyTimeRange.length === 2) {
        self.search.applyStartTime = self.applyTimeRange[0]
        self.search.applyEndTime = self.applyTimeRange[1]
      } else {
        self.search.applyStartTime = ''
        self.search.applyEndTime = ''
      }
    },
    loadInvoiceTable() {
      const self = this
      self.invoice = {}
      self.packSearchData()
      getInvoiceList(self.search)
        .then(response => {
          if (response.data.status === 'success') {
            self.invoiceTableData = response.data.data
          } else {
            self.$message({
              message: '开票列表信息加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    exportInvoice() {
      // 导出发票信息
      const self = this
      exportInvoice(self.search)
        .then(response => {
          debugger
          var fileName = '发票信息' + new Date().getTime()
          download(response.data, 'application/vnd.ms-excel', fileName)
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '导出失败'
          })
        })
    },
    loadInvoiceInfo(row) {
      const self = this
      getInvoice(row)
        .then(response => {
          if (response.data.status === 'success') {
            self.invoice = response.data.data
          } else {
            self.$message({
              message: '开票信息加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    openSkuInfo(row) {
      const self = this
      self.modalData = row
      self.modal = skuInfo
    },
    saveInvoice() {
      const self = this
      const invoiceInfo = { invoice: JSON.stringify(self.invoice) }
      var fromData = self.assemblesFromData(invoiceInfo)
      saveInvoice(fromData)
        .then(response => {
          if (response.data.status === 'success') {
            self.$message({
              message: '开票成功',
              type: 'success'
            })
            self.loadInvoiceTable()
            self.dialogInvoiceVisible = false
          } else {
            self.$message({
              message: '开票失败',
              type: 'warning'
            })
          }
        })
        .catch(() => {
          self.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
    },
    invoiceDialog(index, row) {
      // 点击同一个时，不去查询
      if (this.invoice && this.invoice.id === row.id) {
        this.dialogInvoiceVisible = true
        return
      }
      this.loadInvoiceInfo(row)
      this.dialogInvoiceVisible = true
    },
    invoiceInfoDialog(index, row) {
      // 点击同一个时，不去查询
      if (this.invoice && this.invoice.id === row.id) {
        this.dialogInvoiceInfoVisible = true
        return
      }
      this.loadInvoiceInfo(row)
      this.dialogInvoiceInfoVisible = true
    },
    receiptDialog(index, row) {
      // 点击同一个时，不去查询
      if (this.invoice && this.invoice.id === row.id) {
        this.dialogReceiptVisible = true
        return
      }
      this.loadInvoiceInfo(row)
      this.dialogReceiptVisible = true
    },
    assemblesFromData(data) {
      var fromData = new FormData()
      if (data) {
        for (var prop in data) {
          if (data[prop] !== null) {
            fromData.append(prop, data[prop])
          } else {
            fromData.append(prop, '')
          }
        }
      }
      if (fromData) {
        return fromData
      } else {
        return new FormData()
      }
    }
  }
}
</script>
